package com.eobard.config.thread;

import com.eobard.utils.ThreadUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Eobard Gu
 * @Date: 2025-07-18
 * @Description: TODO
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(ThreadUtils.getCoreSize());
        executor.setMaxPoolSize(ThreadUtils.getMaxSize());
        executor.setQueueCapacity(ThreadUtils.getQueueCapacity());
        executor.setThreadNamePrefix("custom-exec-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());     //直接丢掉任务

        //当Spring应用关闭时（如容器关闭、项目停止）,线程池不会立刻关闭,而是会等待线程池中的任务执行完毕再关闭。
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //最多会等待30秒来完成任务,超过这个时间仍未完成，则强制终止
        executor.setAwaitTerminationSeconds(30);

        //初始化
        executor.initialize();
        return executor;
    }
}
